package org.roger.highlighter;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.TextFragment;
import org.apache.lucene.search.highlight.TokenSources;
import org.roger.search.LuceneSearchBase;
import org.roger.search.SingleSearch;

public class SimpleHighlighter extends AbstractHighlighter{
	
	private LuceneSearchBase search;
	
	private Analyzer analyzer;
	
	private String indexPath;
	
	public SimpleHighlighter(LuceneSearchBase search,Analyzer analyzer,String indexPath){
		this.search = search;
		this.analyzer = analyzer;
		this.indexPath = indexPath;
	}
	
	public TextFragment[][] doHighlight(String field,int num){
		Highlighter highlighter = getHighlighter();
		try {
			TopDocs hits = search.search(indexPath);
			TextFragment[][] frag = new TextFragment[hits.scoreDocs.length][];
			for(int i = 0; i < hits.scoreDocs.length; i++){
				Document doc = search.getSearcher().doc(hits.scoreDocs[i].doc);
				String contents = doc.get(field);
				
				TokenStream tokenStream = analyzer.tokenStream(field, contents);
//				TokenStream tokenStream = TokenSources.getAnyTokenStream(  
//						search.getSearcher().getIndexReader(), hits.scoreDocs[i].doc, field,doc, analyzer);
				frag[i] = highlighter.getBestTextFragments(tokenStream,  
						contents, false, num);
			}
			return frag;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public Formatter getFormatter() {
		return new SimpleHTMLFormatter("<font color='red'>", "</font>"); 
	}

	@Override
	public Query getQuery() {
		return search.getSearchQuery();
	}
	
	public static void main(String[] args) {
		SimpleHighlighter sh = new SimpleHighlighter(new SingleSearch("contents","your"),new StandardAnalyzer(),"D:/index2");
		TextFragment[][] frag = sh.doHighlight("contents",10);
		
		for (int j = 0; j < frag.length; j++) {
			for(int i = 0; i < frag[j].length; i++){
				if ((frag[j][i] != null) && (frag[j][i].getScore() > 0)) {  
	                System.out.println((frag[j][i].toString()));  
	            }
			}
        }
	}
}
